03. Exercise: Generics

Generics Exercise

Create a generic method and generic lists.

Task Description:

Let's get some practice with generics by creating both a generic method and a generic list.

Task List:

Task Feedback:

Nice work!

Solution

ND079 C1 L5 A02b Generic Solutions

Here is the solution for creating a generic method, which displays each of the different Class types.

import java.util.ArrayList;
import java.util.List;

public class GenericsExcercise {

    public static void main(String[] args) {
        ArrayList<Object> variables = new ArrayList<Object>();
        Double doubleNumber = 1.5;
        String name = "Sally";
        int intNumber = 1;
        char letter = 'a';

        variables.add(doubleNumber);
        variables.add(name);
        variables.add(intNumber);
        variables.add(letter);

        for (Object variable : variables) {
            GenericsExcercise.displayClassName(variable);
        }

    }
    static <T> void displayClassName(T variable) {
        System.out.println(variable.getClass().getName());
    }

}